package com.itheima.health.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.itheima.health.dao.RoleDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleDao roleDao;
    @Override
    public List<Role> findAll() {
        return roleDao.selectAll();
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        log.info("[检查组-分页查询]data：{}",queryPageBean);
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //查询page
        Page<Role> page = roleDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(),page.getResult());
    }




    @Transactional
    @Override
    public void add(Role role,Integer[] permissionIds,Integer[] menuIds) {
        roleDao.insert(role);
        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleIdAndPermissionId(role.getId(),permissionId);
        }

        for (Integer menuId : menuIds){
            roleDao.insertMenuIdAndRoleId(role.getId(),menuId);
        }
    }

    @Transactional
    @Override
    public void edit(Role role,Integer[] permissionIds,Integer[] menuIds) {
        roleDao.update(role);
        roleDao.deletePermissionIdByRoleId(role.getId());
        roleDao.deleteMenuIdsByRoleId(role.getId());
        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleIdAndPermissionId(role.getId(),permissionId);
        }

        for (Integer menuId :menuIds){
            roleDao.insertMenuIdAndRoleId(role.getId(),menuId);
        }
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.selectById(id);
    }

    @Override
    public void delete(Integer id) {
        long menuCount = roleDao.countMenuIdByRoleId(id);
        long permissionCount = roleDao.countPermissionIdRoleId(id);

        if(menuCount>0|| permissionCount>0){
            throw new BusinessRuntimeException("数据有关联 不能删除");
        }

        roleDao.delete(id);
    }

    @Override
    public List<Integer> findRoleIdsByMenuId(Integer id) {
        return roleDao.selectRoleIdsByMenuId(id);
    }


}
